我试图将匹配特定文件的文件名分隔成一个单独的文件,并将其内容分成与特定模式匹配的不同文件。我的文件名包含特殊字符,如“|”
我尝试使用grep命令。 Grep Ril和Grep -H打印文件名,但它不起作用。
#!bin/bash
cd home/test
let "x = 1"
for file in $(find home/test/* -type f -name "*.txt") ;
do
var=$(echo "${x}|fill|${file##*/}")
echo "${var}" | grep -n "*|fill|*.txt" >header.txt
myvar=$(sed 's/^/'${x}'|/g' ${file})
echo "${myvar}" |grep -n "*|Ball|*" >Ball.txt
echo "${myvar}" |grep -n "*|Fire|*" >Fire.txt
let x=x+1
done
unset 'x'
let x=x+1
done
unset 'x
我有这种格式的文件名:
1|fill|abc.txt
2|fill|def.txt
'fill'在所有文件中保持不变。这个的最终文件应该有这样的值
1|fill|abc.txt
2|fill|def.txt
3...
4...
5...
etc...
然后,每个文件包含不同的内容。
File1包含与此模式类似的数据:
1|Ball|202029|
1|Cat|202029|
1|fire|202898
...
文件2包含与此模式类似的数据:
2|Bat|202029|
2|Ball|202029|
2|cat|202898
现在最后的输出应该是这样的,所有包含'ball'的数据应该在一个单独的文件中,'cat'在单独的文件中,'fire'在单独的文件中,依此类推。
我不确定下面的代码会做你想要的东西,但它会接近我,我知道,我相应更新。
下面的文件将与您在脚本中使用的其他文件位于同一目录中,并且当它们结束.txt时,下一个脚本运行也将读取它们。
header.txt
B.txt
C.txt
F.txt
#!/bin/bash
# i put the directory in variable, so it can be changed at a single place.
dir='/home/test'
#if cd failed , print erron on standard error output and terminate script.
if ! cd "${dir}" ;then
echo "cd failed into ${dir}" >&2
exit 1
fi
# set counter to 1
let "x = 1"
# Null file contents or create new file
# without this file content will be preserved from earlier script runs.
> header.txt
> B.txt
> C.txt
> F.txt
# go trhought every file in ${dir} path that name end with .txt and it is a regular file
for file in $(find ${dir} -type f -name "*.txt") ;
do
# store basefilename in variable with aditional counter number and text |Fill| front of it.
filename=$(echo "${x}|fill|${file##*/}")
echo "${filename}" >> header.txt
# this can be used as well:
##echo "${x}|fill|${file##*/}" >> header.txt
# only difference is you stored the output into variable.
# find matching line in files
grep -i '|Ball|' ${file} | sed 's/^/'${x}'|/g' >> B.txt
grep -i '|Cat|' ${file} | sed 's/^/'${x}'|/g' >> C.txt
grep -i '|Fire|' ${file} | sed 's/^/'${x}'|/g' >> F.txt
# add 1 to counter
let "x=x+1"
done
# unset counter
unset 'x'
输入文件:
FILE1.TXT
1|Ball|202029|
1|Cat|202029|
1|fire|202898
FILE2.TXT
2|Bat|202029|
2|Ball|202029|
2|cat|202898
输出文件:
header.txt
1|fill|header.txt
2|fill|B.txt
3|fill|C.txt
4|fill|F.txt
5|fill|File1.txt
6|fill|File2.txt
B.txt
5|1|Ball|202029|
6|2|Ball|202029|
C.txt
5|1|Cat|202029|
6|2|cat|202898
F.txt
5|1|fire|202898