Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

Bash - Remove the last character of the line this before?

I am trying to format a database script and I need to remove the last " , " from the lines that are before ")," but I have not been successful ...

This is the input file

DROP TABLE IF EXISTS attribute_type;
CREATE TABLE attribute_type (
  attribute_type_id int(11) NOT NULL,
  name varchar(30) COLLATE es_CO.UTF-8 NOT NULL,
  description text COLLATE es_CO.UTF-8,
  is_set smallint(6) DEFAULT NULL,    <-- Here is the last character I want to remove
),


DROP TABLE IF EXISTS attribute_type_options;
CREATE TABLE attribute_type_options (
  attribute_type_options_id int(11) NOT NULL,
  person_attribute_type_id int(11) DEFAULT NULL,
  name varchar(60) COLLATE es_CO.UTF-8 NOT NULL,
  default_value bit(1) DEFAULT NULL,    <-- Here is the last character I want to remove
),

This should be the output

DROP TABLE IF EXISTS attribute_type;
CREATE TABLE attribute_type (
  attribute_type_id int(11) NOT NULL,
  name varchar(30) COLLATE es_CO.UTF-8 NOT NULL,
  description text COLLATE es_CO.UTF-8,
  is_set smallint(6) DEFAULT NULL
),


DROP TABLE IF EXISTS attribute_type_options;
CREATE TABLE attribute_type_options (
  attribute_type_options_id int(11) NOT NULL,
  person_attribute_type_id int(11) DEFAULT NULL,
  name varchar(60) COLLATE es_CO.UTF-8 NOT NULL,
  default_value bit(1) DEFAULT NULL
),

I tried this solution but it does the change in all lines , not just where I need Thank you for your help !!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try doing this :

perl -0pe 's/,s*
)/
)/g' file

NOTE

  • -0 permit perl to read the whole file instead of line by lines
  • -p is like using while (<>) {} construct and print each lines like sed
  • s/, )/ )/g is a regex substitution

Another solution

using pure :

while read line; do
    if [[ $line =~ ^),s* ]]; then
        echo "${lastline%,}"
    else
        echo "$lastline"
    fi

    lastline="$line"
done < file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...