从shell脚本中的每一行获取前5个字符

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)


Wil*_*ell 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
Run Code Online (Sandbox Code Playgroud)

  • 如果唯一的命令是 `echo`,那么 while 循环是完全没有必要的,但我认为在由占位符保存的实际脚本中发生了更多的事情:`#code 用于将 id 作为参数传递给其他脚本文件` (2认同)