这是我的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我该怎么做?
发布于 2014-01-07 11:58:58
如果您想以这种方式使用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"发布于 2014-01-07 12:11:48
嗯,这是一个单线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发布于 2014-01-07 12:11:04
与其将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
donehttps://stackoverflow.com/questions/20970975
复制相似问题