bash how to read a single line or filenames with spaces solution


This happens all the time, you are reading from a textfile which has spaces eg:

datainfo 00
datainfo 11

If you do loop on it like this:
for info in `cat $file`; do
  echo "info=$info"
done


It will treat datainfo and 00 as two separate lines:

info=datainfo
info=00

Obviously that's not what we want and there are many weird solutions in bash but I'll try and pick what I feel is the simplest and most practical.

My favorite solution:

The key is setting the IFS as below and changing the default delimiter from space " " to newline or \n. You can use the same code and it tells bash to understand not to see a " " space as a delimiter so only a newline is counted.   In plain English this makes it so files and directories with spaces are interpreted as intended.

IFS=$(echo -en "\n\b")

for info in `cat $file`; do
  echo "info=$info"
done

 

Solution #2
while read -r; do
  line=$REPLY
  id=`echo $line|cut -f 2 -d " "`
  ip=`echo $line|cut -f 1 -d " "`
done < migratelist.txt


Tags:

bash, filenames, spaces, textfile, eg, datainfo, info, echo, quot, solutions, ll, simplest, ifs, default, delimiter, newline, counted, directories, interpreted, en, reply, ip, migratelist, txt,

Latest Articles

  • Convert-im6.q16: attempt to perform an operation not allowed by the security policy `PDF' @ error/constitute.c/IsCoderAuthorized/413. convert-im6.q16: no images defined `pts-time.jpg' @ error/convert.c/ConvertImageCommand/3258. solution ImageMagick P
  • Apache PHP sending expires header solution cannot use cache with CDN
  • How to install virt-manager in Mint 22/Ubuntu 22
  • Infiniband Guide
  • python mysql install error: /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found mysql_config --version
  • FreePBX 17 How To Add a Trunk
  • Docker Container Onboot Policy - How to make sure a container is always running
  • FreePBX 17 How To Add Phones / Extensions and Register
  • Warning: The driver descriptor says the physical block size is 2048 bytes, but Linux says it is 512 bytes. solution
  • Cisco How To Use a Third Party SIP Phone (eg. Avaya, 3CX)
  • Cisco Unified Communication Manager (CUCM) - How To Add Phones
  • pptp / pptpd not working in DD-WRT iptables / router
  • systemd-journald high memory usage solution
  • How to Install FreePBX 17 in Linux Debian Ubuntu Mint Guide
  • How To Install Cisco's CUCM (Cisco Unified Communication Manager) 12 Guide
  • Linux Ubuntu Redhat How To Extract Images from PDF
  • Linux and Windows Dual Boot Issue NIC Won't work After Booting Windows
  • Cisco CME How To Enable ACD hunt groups
  • How to install gns3 on Linux Ubuntu Mint
  • How to convert audio for Asterisk .wav format