How can i add my own value to this script?
echo "Choose column: "
read k
cat file.txt | awk '{print $k}'
CodePudding user response:
You could pass the column number as a variable to awk. Also, no need to use cat
because awk
can read files.
#!/bin/bash
echo "Choose column: "
read -r k
awk -v col="${k}" '{print $(col)}' file.txt
Sample file.txt:
col1 col2 col3
1 2 3
4 5 6
7 8 9
Output:
$ ./script
Choose column:
1
col1
1
4
7
$ ./script
Choose column:
2
col2
2
5
8
$ ./script
Choose column:
3
col3
3
6
9
$ ./script
Choose column:
4
# Note, no columns printed because there are only 3 columns