【问题标题】:selecting a particular word from a file in shell scripts从 shell 脚本中的文件中选择特定单词
【发布时间】:2013-02-02 19:35:49
【问题描述】:

我有一个具有这种结构的文本文件:

....

"/home/letizia/Documents/SpanishSegmentation/Recordings/segmented/mfc/F001.0.rec"
COGE
LAS
HOJAS
Y
LAS
QUEMAS
TODAS
EN
EL
FUEGO
"/home/letizia/Documents/SpanishSegmentation/Recordings/segmented/mfc/F002.0.rec"
LA
LIGA
DE
PAZ
SE
REUNIO314201
PARA
TRATAR
EL
TEMA
....

我想选择“F0001.0”和“F0002.0”。

我正在使用:

     ID="F"
     if [[ "$LINE" == *Recordings* ]]
     then        
     SEGMENT=`echo $LINE | grep -o $ID.* | cut -d'.' -f1-2`
     fi

但它不起作用。哪里错了?

非常感谢您。

【问题讨论】:

    标签: string shell grep


    【解决方案1】:

    尝试改用sed

    sed -n 's@^".*/Recordings/.*/\(.*\)"$@\1@p' file.txt
    

    快速演练:

    1. -n:除非特别要求(最后的p),否则不要打印任何内容。
    2. s@:将直到下一个@ 的部分替换为直到下一个的部分。
    3. ^".*/Recordings/.*/\(.*\)"$:匹配以双引号开头和结尾的行,包含 /Recordings/,并吃掉所有内容,直到最后一个斜杠。
    4. \1:用最后一部分替换匹配的字符串(我们在括号中捕获)。

    【讨论】:

    • 如果您喜欢我的回答,您可以投票支持和/或接受它作为您的首选解决方案。享受 StackOverflow!
    【解决方案2】:

    你需要一个while 循环:

    while IFS= read -r line; do
        id="F"
        if [[ "$line" =~ /Recordings/ ]]; then
    
            segment=$(echo $line | grep -o "$id.*" | cut -d '.' -f1-2)
            echo "$segment"
        fi
    done < file.txt
    

    结果:

    F001.0
    F002.0
    

    但是,更好的方法是使用sed

    sed -n '/Recordings/s#.*/\(F[^\.]*\.[^\.]*\).*#\1#p' file.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 2020-09-20
      相关资源
      最近更新 更多