如果我有一个txt文件,每行包含一个项目,例如fruits.txt。
apples
oranges
bananas
cherries
如何使用 bash 命令行将其转换为另一个txt文件,该文件具有与特定水果相对应的枚举ID,例如fruitids.txt。
item {
id: 1
name: 'apples'
}
item {
id: 2
name: 'oranges'
}
item {
id: 3
name: 'bananas'
}
item {
id: 4
name: 'cherries'
}
答案 0 :(得分:2)
Awk
解决方案:
awk '{ printf "item {\n id: %d\n name: \047%s\047\n}\n",NR,$1 }' fruits.txt > fruitids.txt
最终fruitids.txt
内容:
item {
id: 1
name: 'apples'
}
item {
id: 2
name: 'oranges'
}
item {
id: 3
name: 'bananas'
}
item {
id: 4
name: 'cherries'
}
答案 1 :(得分:1)
尝试:
nl fruits.txt |awk '{print "item {\n" "\t id:" $1"\n \t name:" $2 "\n}"}' > fruitsid.txt
答案 2 :(得分:1)
纯bash
的另一种解决方案:
c=0
while read i; do
c=$((c+1))
echo -e "item {\n id: $c \n name: '$i'\n}"
done < <(cat fruits.txt) >> fruitsid.txt
一衬垫:
c=0; while read i; do c=$((c+1)) && echo -e "item {\n id: $c \n name: '$i'\n}" ; done < <(cat fruits.txt) >> fruitsid.txt
输出:
item {
id: 1
name: 'apples'
}
item {
id: 2
name: 'oranges'
}
item {
id: 3
name: 'bananas'
}
item {
id: 4
name: 'cherries'
}