首页 > 解决方案 > 如果找到关键字,则在行尾附加文件名的一部分

问题描述

我在一个目录中有一组文件。文件名是abc-xyz-v01abc-xyz-v02abc-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

标签: linuxbashshell

解决方案


使用gnu-awk,它可以在一个命令中完成:

awk -i inplace '/name/{split(FILENAME, a, "-"); $0 = $0 "-" a[3]} 1' abc-xyz-v0{1..3} 

推荐阅读