Skip to content

Instantly share code, notes, and snippets.

@zlargon
Last active October 5, 2015 09:24
Show Gist options
  • Save zlargon/1ea439389225db0ca813 to your computer and use it in GitHub Desktop.
Save zlargon/1ea439389225db0ca813 to your computer and use it in GitHub Desktop.
replace "line_number" line to "repace_string" in "file_name"
#!/bin/bash
# function replace (file_name, line_number, replace_string)
replace () {
file=$1
number=$2
string=$3
n=1
cat $file | while read line
do
# empty file
if [[ $n == 1 ]]; then
> $file
fi
# write file
if [[ $number == $n ]]; then
echo $string >> $file
else
echo $line >> $file
fi
# increase counter
n=$(( $n + 1 ))
done
}
# test
replace file.txt 1 "hello1"
replace file.txt 2 "hello2"
replace file.txt 3 "hello3"
replace file.txt 4 "hello4"
cat file.txt
1
2
3
4
5
6
7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment