【问题标题】:Retrieve string between characters and assign on new variable using awk in bash在 bash 中使用 awk 检索字符之间的字符串并分配新变量
【发布时间】:2015-12-20 06:39:24
【问题描述】:

我是 bash 脚本的新手,我正在学习命令的工作原理,我偶然发现了这个问题,

我有一个文件/home/fedora/file.txt

文件里面是这样的:

[apple] This is a fruit.
[ball] This is a sport's equipment.
[cat] This is an animal.

我想要的是检索“[”和“]”之间的单词。

到目前为止我尝试的是:

while IFS='' read -r line || [[ -n "$line" ]];
do
    echo $line | awk -F"[" '{print$2}' | awk -F"]" '{print$1}'
done < /home/fedora/file.txt

我可以打印“[”和“]”之间的单词。

然后我想将回显的单词放入一个变量中,但我不知道如何。

任何帮助我都会感激不尽。

【问题讨论】:

    标签: linux string bash awk terminal


    【解决方案1】:

    除了使用awk,还可以使用bash提供的原生参数扩展/子串提取。下方# 表示从左侧修剪,而% 用于从右侧修剪。 (注意:单个#% 表示删除直到第一次,而##%% 表示删除所有 次):

    #!/bin/bash
    
    [ -r "$1" ] || {    ## validate input is readable
        printf "error: insufficient input. usage: %s filename\n" "${0##*/}"
        exit 1
    }
    
    ## read each line and separate label and value
    while read -r line || [ -n "$line" ]; do
        label=${line#[}     # trim initial [ from left
        label=${label%%]*}  # trim through ] from right
        value=${line##*] }  # trim from left through '[ '
        printf " %-8s -> '%s'\n" "$label" "$value"
    done <"$1"
    
    exit 0
    

    输入

    $ cat dat/labels.txt
    [apple] This is a fruit.
    [ball] This is a sport's equipment.
    [cat] This is an animal.
    

    输出

    $ bash readlabel.sh dat/labels.txt
     apple    -> 'This is a fruit.'
     ball     -> 'This is a sport's equipment.'
     cat      -> 'This is an animal.'
    

    【讨论】:

      【解决方案2】:

      试试这个:

      variable="$(echo $line | awk -F"[" '{print$2}' | awk -F"]" '{print$1}')"
      

      variable="$(awk -F'[\[\]]' '{print $2}' <<< "$line")"
      

      或完成

      while IFS='[]' read -r foo fruit rest; do echo $fruit; done < file
      

      或使用数组:

      while IFS='[]' read -ra var; do echo "${var[1]}"; done < file
      

      【讨论】:

      • 感谢它的工作!我也刚刚了解到这也有效:word=$line word=${word##*[} word=${word%%]*}
      猜你喜欢
      • 2019-12-25
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多