使用sed从空格分隔的字符串中解析特定值


0

我有一个文件,其中包含以下行:

0 6 973 1346 2318 456 431 93 58 1 1 0 0 0 0

我想提取第1,第4和第5个数字并将它们保存在bash中的变量中以供进一步使用。在上面的例子中,我想要的值是'0','1346'和'2318'。

我想用sed但我不知道怎么做。任何其他方式也欢迎。

PS。谢谢你的答案,以下是我现在使用的:

for fn in $(cat filelist); do
  more $fn | \                                                                                                                                                                         
      while read str; do
          echo $str
          var=$(echo $str | awk -F" " '{print $1,$2,$3,$4,$5}')
          set -- $var
          echo $1
          echo $4
          echo $5
  done
done

它有效,是的~~

Answers:


1

cat myFile.txt | 以下脚本:

#!/bin/bash
while read lineOfText
do
    echo $lineOfText | any of the approaches from http://www.unix.com/shell-programming-scripting/38450-split-string-using-separetor.html
done

但我想从文件中逐行读取一行,然后解析该行。我没有可用的字符串
zhanwu 2011年

@zhanwu看到编辑的答案
AlcubierreDrive

读取lineOfText部分花了我一些时间来弄清楚,但最终它的工作原理。thx
zhanwu 2011年

1
while read -r fn
    while read -r first second third fourth fifth remainder
    do
        echo "$first"
        echo "$fourth"
        echo "$fifth"
    done < "$fn"
done < filelist

0

如果我可以提供建议,您可以像这样简化脚本:

for fn in $(< filelist); do  #Replacement for $(cat filelist)
  while read str; do
    echo $str
    # No need for set --, unless you *really* want the values to be
    # placed in $1, $4, and $5
    read var1 var4 var5 <<< "$( echo $str | awk '{print $1,$4,$5}' )"
    echo $var1
    echo $var4
    echo $var5
  done < $fn  # Replaces more $fn |
done
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.