Bash Вставляем в определенной строке текстового файла другой текстовый файл

Bash скрипт, который может вставить один текстовый файл в другой в определенной строке:

#! /bin/sh
#
####

NAME_="insertext"
SYNOPSIS_="scripts.sh [-hl] <n> <file_insert> <file> [<file>..]"

usage() {

echo >&2 "Usage: $SYNOPSIS_
Requires: $REQUIRES_
Options:
<n>, номер строки
<file_insert>, текстовый файл который вставляете
<file>, файл в который вставляем
-h, Помощь"
exit 1
}

# tmp files setup
tmp_1=/tmp/tmp.${RANDOM}$$
tmp_2=/tmp/tmp.${RANDOM}$$

# signal trapping and tmp file removal
trap 'rm -f $tmp_1 $tmp_2 >/dev/null 2>&1' 0
trap "exit 1" 1 2 3 15

# enabling extended globbing
shopt -s extglob

# option handling
case "$1" in
-h) usage ;;
-l) more $0; exit 1 ;;
+([0-9])) # arg1 must be an integer

n=$1
[[ $# < 3 ]] && { echo >&2 missing argument; exit 1; }
[ -e $2 ] || { echo >&2 file $2 does not exist; exit 1; }
insert=$2
shift 2

for a in $@; do

if [ -f $a ]; then

# in case we want to insert at line 1
if [[ $n == 1 ]];then

touch $tmp_1
sed -n ''$n',$p' $a > $tmp_2
cat $tmp_1 $insert $tmp_2 > $a
continue

fi

((n--)) # back up one line
sed -n '1,'$n'p' $a > $tmp_1
((n++)) # back to original n
sed -n ''$n',$p' $a > $tmp_2
cat $tmp_1 $insert $tmp_2 > $a

else

echo $a не существует или это не файл
fi

done ;;

*) echo неверный аргумент, для получения помощи запустите скрипт с параметром -h; exit 1 ;;

esac

 

Leave a Reply

Ваш адрес email не будет опубликован. Обязательные поля помечены *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>