I have a file which contains the following data:
wednesday
Weekday
thursday
Weekday
friday
Weekday
saturday
MaybeNot
sunday
MaybeNot
monday
Weekday
tuesday
Weekday
I would like to insert a string $:$
in front of each alternate line such that the file is rewritten as follows:
wednesday
$:$Weekday
thursday
$:$Weekday
friday
$:$Weekday
saturday
$:$MaybeNot
sunday
$:$MaybeNot
monday
$:$Weekday
tuesday
$:$Weekday
How would I achieve this using awk/sed?
ok. here.
cat << EOF | awk -vRS="" '{print $1 "\n$:$" $2 "\n" }'
wednesday
Weekday
thursday
Weekday
friday
Weekday
saturday
MaybeNot
sunday
MaybeNot
monday
Weekday
tuesday
Weekday
EOF
gives...
wednesday
$:$Weekday
thursday
$:$Weekday
friday
$:$Weekday
saturday
$:$MaybeNot
sunday
$:$MaybeNot
monday
$:$Weekday
tuesday
$:$Weekday
If your file doesn't start with a newline and has newlines as shown in your question then use:
sed -i.bak '2s/^/$.$/;3,${n;n;s/^/$.$/;}' file
If file has no new lines and you want to put $.$
before every alternate line as you state in question:
sed -i.bak 'n;s/^/$.$/' file
To prepend $:$
to every 3rd line starting with line 2 do this with GNU sed:
sed -i '2~3s/^/$:$/' infile
Note that this will overwrite infile
so be careful.
Using awk - the variable n
is initialised in the BEGIN pattern, then the lines are printed as required by testing the odd/eveness of n
.
awk 'BEGIN{n=1}
{
if (n++ % 2)
print $0
else
print "$:$"$0
}' datafile
ssed use perlre, so if you know perlre, it simple. use -i if you want modify target file.
cat t|ssed 's/^\([A-Z]\)/$:$&/'
wednesday
$:$Weekday
thursday
$:$Weekday
friday
$:$Weekday
saturday
$:$MaybeNot
sunday
$:$MaybeNot
monday
$:$Weekday
tuesday
$:$Weekday
awk '/^[[:upper:]]/ {$0="$:$"$0}1' file
to replace in the file
awk '/^[[:upper:]]/ {$0="$:$"$0}1' file > tmp ; mv tmp file
EDIT Another version (this needs the formatting to be the same all time):
awk 'NR%3==2 {$0="$:$"$0} 1' file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.