Home > Enterprise >  Passing parameter as control number and get table name
Passing parameter as control number and get table name

Time:04-06

I have a scenario where there is a file with control number and table name, hereby an example:

1145|report_product|N|N| 
1156|property_report|N|N

I need to pass the control number as 1156 and have to get table name as PR once I get the table name as PR then I need to add some text on that.

Please help

CodePudding user response:

Assuming the controll file is:

# cat controlfile.txt
1145|report_product|N|N
1156|property_report|N|N

To fine some line you can use:

grep 1156 controlfile.txt

If needed you can save it to a variable: result=$(grep 1156 file.txt)

Assuming you need to add append something on this line.... you can use:

sed '/^1156/s/$/ 123/' controlfile.txt

This example will add "123" at the end of line that start with 1156

If needed, add more details like what output you want or anything else to help us better understand your need.

CodePudding user response:

You need to work in two stages:

  1. You need to find the line, containing 1156.
  2. You need to get the information from that line.

In order to find the line (as already indicated by Juranir), you can use grep:

Prompt> grep "1156" control.txt
1156|property_report|N|N

In order to get the information from that line, you need to get the second column, based on the vertical line (often referred as a "pipe" character), for which there are different approaches. I'll give you two:

  1. The cut approach: you can cut a line into different parts and take a character, a byte, a column, .... In this case, this is what you need:

     grep "1156" control.txt | cut -d '|' -f 2
    
     -d '|' : use the vertical line as a column separator
     -f 2   : show the second field (column)
    
  2. The awk approach: awk is a general "text modifier" with multiple features (showing parts of text, performing basic calculations, ...). For this case, it can be used as follows:

     grep "1156" control.txt | awk -F '|' '{print $2}'
    
     -F '|'       : use the vertical line as a column separator
     '{print $2}' : the awk script for showing the second field.
    

Oh, by the way, I've edited your question. You might press the edit button in order to learn how I did this :-)

  •  Tags:  
  • bash
  • Related