sed or awk help or smth...

Hi all,

I will be glad if you can help me.

I have this kind of document:

$cat mistake_file
546488
123456
546887
132548
123456
546887
324645
123456
123456

and I want to replace just first occurence of word or number 123456 in this file with XXXXXX and also to save changes into this file.

it will be not always "123456" and the file is much more longer and this numbers are sometimes in the middle of line... so I want the script in generally not just for this example :slight_smile:

I was trying it with sed but that command replace one occurence in line but on all lines in document or all occurences in documents...

$sed s/123456/XXXXXX/
or
$sed s/123456/XXXXXX/g
or
$sed s/123456/XXXXXX/1

doesn`t worked for me...

I`m not good in awk or nawk but I read somewhere that it should solve my problem... is here anybody who wants and can help? :slight_smile:

Best regards,
oddo :slight_smile:

EDIT: under Solaris (SunOS 5.9)

With awk:

awk '/123456/ && !flag++{print "XXXXXX";next}1' file

Regards

Thanks, but RESULT: awk: syntax error near line 1

maybe I should mentioned that I`m working under Solaris (SunOS 5.9)... :slight_smile:

On Solaris use:

/usr/xpg4/bin/awk

Regards

hm under solaris it is still not working... still the same mistake :frowning:

I tryied it under debian linux and there it is running but, script will just put in stdout XXXXXX not in the file...

any ideas? :smiley:

maybe if it is possible write the script under bash or ksh...

Redirect that to a file.

/usr/xpg4/bin/awk '/123456/ && !flag++{print "XXXXXX";next}1' file > output.txt

It certainly is possible to write a script.

#! /bin/ksh

replaced=0
while read line
do
  if [[ "$line" -eq "123456" -a $replaced -eq 0 ]] ; then
    echo "XXXXXX" >> output.txt
    replaced=1
    continue
  done

  echo "$line" >> output.txt
done < input.txt

THAAAAAAAAAAAANKS A LOT :slight_smile:

awk way solve my problem :slight_smile:

thanks again a lot :slight_smile: you saved lot of my neurons :smiley:

best regards :slight_smile:

aaaah here I go again :frowning:

VAR_1="123456"
VAR_2="XXXXXX"
/usr/xpg4/bin/awk '/$VAR_1/ && !flag++{print "       $VAR_2";next}1' file >output

put me result:

/usr/xpg4/bin/awk: /$VAR_1/: unknown regex error Context is:
>>> /$VAR_1/ <<<

and I need to use there variables... method "'"VAR_1"'" doesn't work too :frowning:

Try this:

VAR_1="123456"
VAR_2="XXXXXX"

/usr/xpg4/bin/awk -v VAR1=$VAR_1 -v VAR2=$VAR_2 '/VAR1/ && !flag++{print "       VAR2";next}1' file >output

Regards

it is doing nothing :o