linux - 如果找到关键字,则在行尾附加文件名的一部分
问题描述
我在一个目录中有一组文件。文件名是abc-xyz-v01
、abc-xyz-v02
等abc-xyz,v03
。在文件中,如果存在关键字“ name
”,那么我必须附加文件名的最后一部分,例如v01
在该行中。
这是我编写的代码,它工作正常,但是有没有更优雅和更好的解决方案。我是 bash 脚本的新手。
#!/bin/bash
# fileinfo.sh
FILES="/home/user/data/test/*"
for file in $FILES
do
echo "$file"
x=0
first=1
linenum=$(awk '/name/{ print NR; exit }' $file)
substr=$(echo $file | cut -d'-' -f 3)
cat $file | while read line; do
x=$(( x+1 ))
if [ $x -eq $first ]
then echo $line > temp.txt
elif [ $x -eq $linenum ]
then echo $line-$substr >> temp.txt
else
echo $line >> temp.txt
fi
done
mv temp.txt $file
done
解决方案
使用gnu-awk
,它可以在一个命令中完成:
awk -i inplace '/name/{split(FILENAME, a, "-"); $0 = $0 "-" a[3]} 1' abc-xyz-v0{1..3}
推荐阅读
- angular-validation - 在不使用多个 *ngIf 的情况下以角度反应形式显示错误消息的更好和更有效的方法
- java - Java - equals() 和 hashCode() 实现
- netsuite - 如何使用 Suitescript 2.0 在 netsuite 中设置 RESTlet 的日期
- active-directory - 使用 ldapsearch 查询 Samba AD 服务器失败并出现 ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)
- php - 如何访问对象属性(arraycollection)?
- python - 通过 ODBC 修改现有的 MS Access 查询
- c++ - 在 lambda 中包装并执行 packaged_task
- three.js - 填充 Vector3 数组
- ruby-on-rails - Rails Button_tag 不提交编辑表单,但提交新表单
- jira - JQL - 在评论中多次搜索关键字