我try 使用命令sed
或awk
,以及定义为Bash脚本的任意函数(或命令).例如,下面的Bash脚本prepend_largest_prime.sh
接受一个字符串作为其第一个参数,并输出N以下较大的素数,其中N是该字符串的长度:
#!/bin/bash
is_prime() {
# Returns 1 if a number is prime, 0 if not
i=2
if [ $1 -lt 2 ]
then
return 0
fi
max=`echo "sqrt($1)" | bc`
while [ $i -le $max ]
do
if [ `expr $1 % $i` -eq 0 ]
then
return 0
fi
i=`expr $i + 1`
done
return 1
}
largest_prime_under() {
counter=$1
is_prime $counter
counter_primeQ=$?
if [[ $counter_primeQ = 1 ]]; then
echo $counter
exit 1
fi
counter=$[ $counter - 1 ]
while [[ $counter -gt 0 ]] ; do
is_prime $counter
counter_primeQ=$?
if [[ $counter_primeQ = 1 ]]; then
echo "$counter"
exit 1
fi
counter=$[ $counter - 1 ]
done
}
string_length() {
str="$1"
n=${#str}
echo "$n"
}
string_length_num=$(string_length "$1")
largest_prime_under_string=$(largest_prime_under $string_length_num)
echo $largest_prime_under_string $1
此脚本的示例调用可以是:
$ ./prepend_largest_prime.sh 'The quick brown fox jumps over the lazy dog.'
43 The quick brown fox jumps over the lazy dog.
这里传递的字符串有44个字符,44以下较大的素数是43.
这就是我所能做的一切.它仍然不起作用,对手头的任务来说似乎太复杂了:
cat input_file.txt
The majestic mountains towered over the quaint little beautiful village below.
The serene garden is colorful.
The old oak trees stood tall, their branches reaching towards the sky.
$ sed "s|.*|\"\$(\./prepend_largest_prime.sh '&')\"|" input_file.txt
"$(./prepend_largest_prime.sh 'The majestic mountains towered over the quaint little beautiful village below.')"
"$(./prepend_largest_prime.sh 'The serene garden is colorful.')"
"$(./prepend_largest_prime.sh 'The old oak trees stood tall, their branches reaching towards the sky.')"
对于本例,我要查找的命令的输出应该是
73 The majestic mountains towered over the quaint little beautiful village below.
29 The serene garden is colorful.
67 The old oak trees stood tall, their branches reaching towards the sky.
我怎样才能做到这一点呢? 谢谢!