我是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
我可以打印&#34; [&#34;和&#34;]&#34;。
然后我想把回音的词放到一个变量中,但我不知道怎么做。
我将不胜感激的任何帮助。
答案 0 :(得分:0)
试试这个:
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
答案 1 :(得分:0)
除了使用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.'