我需要同时将包含特定信息的新行添加到一个或多个文件中。
我尝试使用以下脚本自动执行此任务:
for i in /apps/data/FILE*
do
echo "nice weather 20190830 friday" >> $i
done
它可以完成工作,但我希望我可以使其更多自动化,并让脚本要求我提供文件名和要添加的行。
我希望输出像
enter file name : file01
enter line to add : IWISHIKNOW HOWTODOTHAT
谢谢大家。
答案 0 :(得分:1)
为了阅读用户输入,您可以使用
read user_input_file
read user_input_text
read user_input_line
您可以使用echo -n
根据需要在问题之前打印:
echo -n "enter file name : "
read user_input_file
echo -n "enter line to add : "
read user_input_text
echo -n "enter line position : "
read user_input_line
为了在所需位置添加行,您可以使用head
和tail
“玩”
head -n $[$user_input_line - 1] $user_input_file > $new_file
echo $user_input_text >> $new_file
tail -n +$user_input_line $user_input_file >> $new_file
答案 1 :(得分:1)
对于自动化,要求交互式输入是可怕的。制作一条接受消息和文件列表的命令,以代替命令行参数。
#!/bin/sh
msg="$1"
shift
echo "$msg" | tee -a "$@"
用法:
scriptname "today is a nice day" file1 file2 file3
交互使用的好处是显而易见的-您可以使用Shell的历史记录机制和文件名补全(通常绑定到制表符),但在此基础之上再构建更复杂的脚本要容易得多。
将消息放在第一个命令行参数中的设计使新手感到困惑,但是允许进行非常简单的总体设计,其中“其他参数”(零个或多个)是您要操作的文件。了解grep
如何设计,sed
以及许多其他标准Unix命令。
答案 2 :(得分:0)
您可以使用read
语句提示输入,
read
确实使脚本通用,但是如果要使其自动化,则必须具有一个随附的expect
脚本才能为read
语句提供输入。
相反,您可以在脚本中输入参数,以帮助您实现自动化。.无需提示...
#!/usr/bin/env bash
[[ $# -ne 2 ]] && echo "print usage here" && exit 1
file=$1 && shift
con=$1
for i in `ls $file`
do
echo $con >> $i
done
要使用:
./script.sh "<filename>" "<content>"
引号对于内容很重要,因此内容中的空格被视为内容的一部分。对于文件名,请使用引号,以使外壳程序在调用脚本之前不会对其进行扩展。
示例:./script.sh "file*" "samdhaskdnf asdfjhasdf"