I have a file with this structure:
picture1_123.txt
picture2_456.txt
picture3_789.txt
picture4_012.txt
I wanted to get only the first segment of the file name, that is, picture1 to picture4. I first used the following code:
cat picture | while read -r line; do cut -f1 -d "_"; echo $line; done
This returns the following output:
picture2
picture3
picture4
picture1_123.txt
This error got corrected when I changed the code to the following:
cat picture | while read line; do s=$(echo $line | cut -f1 -d "_"); echo $s; done
picture1
picture2
picture3
picture4
Why in the first:
- The lines are printed in a different order than the original file?
- no operation is done on picture1_123.txt and picture1 is not printed?
Thank you!
cutcommand is reading the entire rest of stdin, so nothing is left for the nextreadcommand.cutcontents inlineonly, and save the result back toline, that might instead beline=$(cut -f1 -d "_" <<<"$line")-- but don't do that, starting a new copy ofcutper line of input is horribly inefficient.echo $lineis itself buggy. Always, always quote your expansions, as inecho "$line"; see I just assigned a variable, butecho $variableprints something else! -- or try testing with a file named*_foo.txt