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

Latest Articles

  • Centos 7 - Convert Minimal to Graphical GUI GNOME or KDE Desktop
  • AMD Set Fan Speed and Other Powerplay Memory/CPU Timings with a Linux script
  • Ethereum Mining Claymore Nanopool Error
  • genisoimage errors with long filenames and deep directory structures
  • Linux Kernel USB Export Errors
  • How to download gajim 0.16.9 XMPP/Jabber client so you can use OMEMO encryption
  • HP DL385 G7 Linux BIOS Update Flash
  • hwloc-nox set CPU affinity in Linux
  • Firefox An error occurred during a connection to some-ip-or-domain. SSL peer reports incorrect Message Authentication Code. Error code: SSL_ERROR_BAD_MAC_ALERT Solution
  • Proxmox understanding the directory structure and why an NFS datastore appears to be missing files/isos
  • pandoc convert markdown to html
  • Proxmox error uploading an iso solution
  • Cannot install moodle
  • MySQL change for Antelope format to Barracuda error solution
  • vmkping -I vmk1 10.0.2.69 PING 10.0.2.69 (10.0.2.69): 56 data bytes sendto() failed (Host is down)
  • gvfs mount in /run/user cannot be accessed or displayed wrong permissions
  • VMWare vSphere 6.7 Errors Solution 503 Service Unavailable (Failed to connect to endpoint:
  • How To Enable Nested KVM so guests can virtualize with hardware extensions
  • vi error solution E166: Can't open linked file for writing
  • Supermicro IPMI / KVM / BMC Remote Console Screen Resizing Issue - Window Cut Off Solution