The Only Neo
The Only Neo

Reputation: 3

How to modify a file according to user input in bash

I've a file with the below contents

A     B     C
1     2     3
4     5     6
7     8     9

Lets say the user input 1 Then the file should change to

A     B     C
X     2     3
4     5     6
7     8     9

Or if the user input 1,2 Then the file should change to

A     B     C
X     X     3
4     5     6
7     8     9

I'm new to bash so any help is appreciated

Upvotes: 0

Views: 1262

Answers (2)

karakfa
karakfa

Reputation: 67467

awk to the rescue!

$ awk -v cols="$cols" 'NR==2{n=split(cols,f,","); 
                             for(i=1;i<=n;i++) sub($i,"X")}1' file

assumes your user input is assigned to the bash variable cols. Pass the values to awk under the same name. Find the values and substitute one at a time only for the second row; print all rows.

Upvotes: 1

A.Villegas
A.Villegas

Reputation: 517

we supposse that the data file names matrix.txt and we make a script to edit the content of the data file.

matrix.txt:

A     B     C
1     2     3
4     5     6
7     8     9

And we make this script:

matrix_script.sh:

read -p "Input: " input
sed "s/$input/X/g" matrix | tee matrix

this changes the number that you write by a 'X'.

The read command reads from keyboard until you press 'Enter'. The '-p' option writes a message before you can write. The 'input' variable is where the 'read' command stores the value that you wrote.

The 'sed' command is for replace the a character for other. We said to sed that we want to replace the value of the 'input' variable for the 'X' character in the 'matrix' file. This copy the content of the matrix file with the changes but no write the changes on the input file. To fix this, we duplicate the output (with the 'tee' command) of the sed command, and one of these outputs will write on the 'matrix' file.

Try it and talk to us if this script works as you want.

Bye

Upvotes: 0

Related Questions