我相信标题是不言自明的。我有一些文件作为参数给出,给定的字符串是我的脚本的最后一个参数。我已经尝试过下面的两个脚本,但不知道如何使它们都工作。我觉得我在两个脚本中都缺少一些“\”字符,我在 sed 命令中指定要找到的模式(字符串)。
#!/bin/bash
a=${@: -1} # get last parameter into a variable
or ((i=1; i<$#; i++)) # for each parameter, except the last one
do
sed -i '1,30{/$a/d}' "${!i}" # delete each line in the i-th file, in range 1-30
# containing $a (last given parameter)
done
第二次尝试:
#!/bin/bash
a=${@: -1} # get last parameter into a variable
for file in "${@:1:$# - 1}"
do
sed -i '1,30{/$a/d}' $file
done
答案1
我的问题是我没有使用双引号,而是使用单引号;所以变量扩展不可能。
这是两个工作脚本,以及 @guillermo chamorro 要求的输入和输出文件以及从终端调用脚本的示例(不确定我是否在这里正确使用了“调用”一词;假设是“使用”):
文件1(文件2具有相同的内容)
Out of the first 30 lines of this file I will be deleting only those that contain
the character substring given as a parameter.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
30
31
32
33
...
and so on
函数_shell_1
#!/bin/bash
a=${@: -1} # store last argument in a variable
#part of the for-loop line is commented because of the first hashtag character
for ((i=1; i<$#; i++)) # consider all arguments, but the last one
do
sed -i "1,30{/$a/d}" "${!i}"
# for each i-th line among the first 30 lines, do in-place deletions
#(-i dictates the in-place part) of each one containing the value of the
# a variable
done
函数_shell_2(仅对 for 循环进行了微小的更改)
#!/bin/bash
a=${@: -1} # store last argument in a variable
for fisier in "${@:1:$# - 1}" # consider all arguments, but the last one
do
sed -i "1,30{/$a/d}" $fisier
# for each i-th line among the first 30 lines, do in-place deletions
#(-i dictates the in-place part) of each one containing the value of the
# a variable
done
脚本命令示例:
./function_shell_1 file1 file2 '2'
#./function_shell_2 file1 file2 '2'
上述两者的工作原理完全相同,在两者中产生相同的预期变化文件1和文件2, IE:
Out of the first 30 lines of this file I will be deleting only those that contain
the character substring given as a parameter.
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
19
31
32
33
...
and so on