use*_*247 17 linux bash shell cut sh
这是我的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
Run Code Online (Sandbox Code Playgroud)
我必须编写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"
Run Code Online (Sandbox Code Playgroud)
但它不起作用这给了我错误
cut: 31113: No such file or directory
cut: 70:54:D2 No such file or directory
31114
31111
31112
: No such file or directory
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
fed*_*qui 27
如果你想使用cut这种方式,你需要使用重定向<<<(这里的字符串),如:
var=$(cut -c-5 <<< "$line")
Run Code Online (Sandbox Code Playgroud)
注意使用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"
Run Code Online (Sandbox Code Playgroud)
tux*_*dna 18
好吧,它是一个单行cut -c-5 sample.txt.例:
$ cut -c-5 sample.txt
31113
31114
31111
31112
Run Code Online (Sandbox Code Playgroud)
从那里开始,您可以将它传递给任何其他脚本或命令:
$ cut -c-5 sample.txt | while read line; do echo Hello $line; done
Hello 31113
Hello 31114
Hello 31111
Hello 31112
Run Code Online (Sandbox Code Playgroud)
而不是管道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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45018 次 |
| 最近记录: |