0

I'm currently trying to find a line in a file

#define IMAX 8000

and replacing 8000 with another number.

Currently, stuck trying to pipe arguments from awk into sed.

grep '#define IMAX' 1d_Euler_mpi_test.c | awk '{print $3}' | sed

Not too sure how to proceed from here.

1
  • Oops my bad! Sorry. Commented Nov 1, 2018 at 5:47

3 Answers 3

1

I would do something like:

sed -i '' '/^#define IMAX 8000$/s/8000/NEW_NUMBER/' 1d_Euler_mpi_test.c
Sign up to request clarification or add additional context in comments.

Comments

1

Could you please try following. Place new number's value in place of new_number too.(tested this with GNU sed)

echo "#define IMAX 8000" | sed -E '/#define IMAX /s/[0-9]+$/new_number/'

In case you are reading input from an Input_file and want to save its output into Input_file itself use following then.

sed -E '/#define IMAX /s/[0-9]+$/new_number/' Input_file

Add -i flag in above code in case you want to save output into Input_file itself. Also my codes will catch any digits which are coming at the end of the line which has string #define IMAX so in case you only want to look for 8000 or any fixed number change [0-9]+$ to 8000 etc in above codes then.

1 Comment

I always forget about the capital E flag and it's always nice to see
0

You may use GNU sed.

sed -i -e 's/IMAX 8000/IMAX 9000/g' /tmp/file.txt

Which will invoke sed to do an in-place edit due to the -i option. This can be called from bash.

If you really really want to use just bash, then the following can work:

while read a ; do echo ${a//IMAX 8000/IMAX 9000} ; done < /tmp/file.txt > /tmp/file.txt.t ; mv /tmp/file.txt{.t,}

This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The move at the end just moves temporary to the original name.

3 Comments

I think this will mess up the constant. Shouldn't it be IMAX 9000?
Note that your usage of -i implies GNU sed. The question didn't specify a variant. For that reason and to retain value to a wider audience, you might want to provide more portable usage, or at least clarify that what tooling is required to make use of your answer.
Updated the response to specify GNU sed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.