从文件名中提取一些部分作为变量

Extract some part from filename as variable

我已经阅读了一些关于从文件名中提取某些部分的帖子,但仍然无法解决我的问题。 有一些文件名为 aa - bb.txtcc - dd.txtee - ff.txt 等。 每个文件的最后一行是这样的:

somewordbbaa

对于 aa - bb.txt 和对于 cc - dd.txt 是:

somewordddcc

那么在ee - ff.txt中是:

somewordffee

我想写一个shell脚本来删除各自文件最后一行的bbaa、ddcc、ffee。我试过以下:

#!/bin/bash
for file in *.txt
do
  artist=`echo $file | awk -F'[ .]' '{print }'`
  name=`echo $file | awk -F'[ .]' '{print }'`
  echo $artist >> artist
  echo $name >> name
  sed -i "s/$name$artist//" $file
done

在我运行它之后,它抛出了这个

sed: can't read aa: No such file or directory
sed: can't read -: No such file or directory
sed: can't read bb.txt: No such file or directory
sed: can't read cc: No such file or directory
sed: can't read -: No such file or directory
sed: can't read dd.txt: No such file or directory
sed: can't read ee: No such file or directory
sed: can't read -: No such file or directory
sed: can't read ff.txt: No such file or directory

我也试过这个

#!/bin/bash
ls *.txt | sed 's/\.txt//' > full_name
cut -f1 -d" " full_name > artist
cut -f3 -d" " full_name > name

for file in `ls -1 *.txt`, item1 in artist, item2 in name #Is this right?
do
  tail -n -1 $file | sed 's/$item2$item1//' > $file.last #just the last line
done

刚显示这个,一直按Ctrl+c

才反应过来
tail: cannot open `aa' for reading: No such file or directory

我觉得bash把文件名的空格作为分隔符,把$file读成aa-bb.txt

谁能给我一些建议?

因为您的文件名称中有 space,请尝试您的原始脚本,但更改此行:

sed -i "s/$name$artist//" $file

对此:

sed -i "s/$name$artist//" "$file"