我已经阅读了一些关于从文件名中提取部分内容的线程,但仍然无法解决我的问题。
有一些名为aa - bb.txt
,cc - dd.txt
,ee - 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 $1}'`
name=`echo $file | awk -F'[ .]' '{print $3}'`
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
。
有人能给我一些建议吗?
答案 0 :(得分:1)
由于您的文件名称中有空格,请尝试使用原始脚本,但更改此行:
sed -i "s/$name$artist//" $file
到此:
sed -i "s/$name$artist//" "$file"