以下是 sample.txt 文件,其中包含以下内容
31113 70:54:D2 - a-31003
31114 70:54:D2 - b-31304
31111 4C:72:B9 - c-31303
31112 4C:72:B9 - d-31302
我必须编写shell脚本,因为我将前5个字符(例如31113)作为输入id传递给其他脚本。为此,我试过这个
#!/bin/sh
filename='sample.txt'
filelines=`cat $filename`
while read -r line
do
id= cut -c-5 $line
echo $id
#code for passing id to other script file as parameter
done < "$filename"
但它不起作用这给我错误
cut: 31113: No such file or directory
cut: 70:54:D2 No such file or directory
31114
31111
31112
: No such file or directory
我该怎么做?
答案 0 :(得分:24)
如果您想以这种方式使用cut
,则需要使用redirection <<<
(此处为字符串),如:
var=$(cut -c-5 <<< "$line")
请注意使用var=$(command)
表达式而不是id= cut -c-5 $line
。这是将命令保存到变量中的方法。
另外,使用/bin/bash
代替/bin/sh
让它运作。
对我有用的完整代码:
#!/bin/bash
filename='sample.txt'
while read -r line
do
id=$(cut -c-5 <<< "$line")
echo $id
#code for passing id to other script file as parameter
done < "$filename"
答案 1 :(得分:17)
嗯,它是一个单行cut -c-5 sample.txt
。例如:
$ cut -c-5 sample.txt
31113
31114
31111
31112
从那里开始,你可以将它传递给任何其他脚本或命令:
$ cut -c-5 sample.txt | while read line; do echo Hello $line; done
Hello 31113
Hello 31114
Hello 31111
Hello 31112
答案 2 :(得分:7)
而不是将echo
汇总到cut
,只需将cut
的输出直接传递给while循环:
cut -c 1-5 sample.txt |
while read -r id; do
echo $id
#code for passing id to other script file as parameter
done
答案 3 :(得分:2)
也许你需要这个,awk可以自动识别空白区域。
awk '{print $1}' sample.txt
答案 4 :(得分:2)
请查看以下简单示例:
while read line; do id=$(echo $line | head -c5); echo $id; done < file
其中head -c5
是从字符串中获取前5个字符的正确命令。
答案 5 :(得分:1)
如果您尝试从文件中获取第一列,请尝试awk
:
#!/bin/sh
filename='sample.txt'
while read -r line
do
id=$(echo $line | awk '{print $1}')
echo $id
#code for passing id to other script file as parameter
done < "$filename"
答案 6 :(得分:0)
比最佳答案简单得多:
#!/bin/bash
filename='sample.txt'
while read -r line; do
id=${line:0:5}
echo $id
#code for passing id to other script file as parameter
done < "$filename"
答案 7 :(得分:0)
将sed
与匹配前5个字符的捕获组一起使用,并仅返回该组:
sed -E 's/(.{0,5}).*/\1/' sample.txt
(.{0,5})
贪婪地匹配任何字符,最多5次,并创建一个捕获组。
.*
与该行的其余部分匹配,因为我们要替换整行,而不仅仅是捕获组。
\1
是指向第一个捕获组的反向引用。
因此,我们正在捕获所需的5个字符组,然后仅用该捕获组替换整个匹配的行。