这是我的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
我怎样才能做到这一点?
如果要使用cut
这种方式,则需要使用重定向<<<
(此处为字符串),例如:
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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句