开发者

Bash script to read a file

开发者 https://www.devze.com 2023-01-07 06:40 出处:网络
Not sure why the last line does not cut the \" from the script: #!/bin/bash FILENAME=$1 while read line do

Not sure why the last line does not cut the " from the script:

#!/bin/bash

FILENAME=$1
while read line
do
cut -d '"' -f2
echo $line
done < $FILENAME

$ cat file

"1" test
"2" 开发者_开发知识库test
"3" test
"4" test
"5" test

If I run this script with the following command:

$ ./test file

2
3
4
5
"1" test


The loop executes once.

  • It reads "1" test into variable $line.
  • It executes cut -d '"' -f2 which reads lines 2-5 of the file (because that is the standard input at the time) and prints the number.
  • It echoes what it read as the first line.

Fix:

cut -d '"' -f2 $FILENAME

If, on the other hand, you want to get the numbers into a variable, you could do this in a variety of ways, including:

cut -d '"' -f2 $FILENAME |
while read number
do  # What you want
    echo $number
done

or:

while read line
do
    number=$(echo "$line" | cut -d '"' -f2)
    echo $number
done


Bash can do all the work for you. There's no need for cut:

#!/bin/bash

FILENAME=$1
while read -r -a line
do
    echo ${line//\"}
done < "$FILENAME"

That reads the line into an array, then treats the array as a scalar which gives you the first element. Then the brace expansion in the echo strips out the quotation marks.

Or you can let cut do all the work and give Bash a long coffee break:

FILENAME=$1
cut -d '"' -f2 "$FILENAME"

Always quote variables that contain filenames.


Jonathan Leffler's given you a simpler method (which will also be more efficient), but in case this is a simplification for something you're going to expand on (where just calling cut won't do what you want), and just to demonstrate the principle anyway, your code would need to be fixed up to feed each line to stdin explicitly as follows:

#!/bin/bash

FILENAME=$1
while read line
do
    echo $line | cut -d '"' -f2
done < $FILENAME


like dennis mentioned, there's no need to use external commands

$ while read -r line; do  set -- $line;  echo ${1//\"/}; done<file
1
2
3
4
5

But external commands runs faster if you have very large files.

$ cut -d'"' -f2 file
1
2
3
4
5
$ awk -F'"' '{print $2}' file
1
2
3
4
5
$ sed 's/^"//;s/".*//' file
1
2
3
4
5
0

精彩评论

暂无评论...
验证码 换一张
取 消